package com.ly.juc;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @Classname ForkJoinCalculate
 * @Description TODO
 * @Date 2020/9/29 16:34
 * @Author 冷心影翼
 */
public class ForkJoinCalculate extends RecursiveTask<Long> {

	private long start;

	private long end;

	private static final long THRESHOLD = 10000;


	public ForkJoinCalculate(long start,long end) {
		this.start = start;
		this.end = end;
	}
	
	@Override
	protected Long compute() {
		long lenth = end - start;

		if(lenth <= THRESHOLD) {
			long sum = 0;
			for (long i = start; i <= end ; i++) {
				sum+=i;
			}
			return sum;

		}else {
			long mid  = (start + end)/2;
			ForkJoinCalculate res1 = new ForkJoinCalculate(start,mid-1);
			res1.fork();//拆分子任务
			ForkJoinCalculate res2 = new ForkJoinCalculate(mid,end);
			res2.fork();
			return res1.join()+res2.join();
		}

	}

	public static void main(String[] args) {
		ForkJoinCalculate joinCalculate = new ForkJoinCalculate(1,10000000);
		System.out.println(joinCalculate.compute());

		Instant start = Instant.now();
		long reduce = LongStream.rangeClosed(0, 1000000000L).parallel().reduce(0, Long::sum);
		System.out.println(reduce);
		Instant end = Instant.now();
		System.out.println(Duration.between(start,end).toMillis());

		Instant start2 = Instant.now();
		long reduce2 = LongStream.rangeClosed(0,1000000000L).reduce(0, Long::sum);
		System.out.println(reduce2);
		Instant end2 = Instant.now();
		System.out.println(Duration.between(start2,end2).toMillis());
	}
}
